package com.service;

import com.entity.FinanceAccount;
import com.entity.FinanceFlow;
import com.repository.FinanceAccountRepository;
import com.repository.FinanceFlowRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class FinanceAccountService {

    @Autowired
    private FinanceAccountRepository accountRepository;

    @Autowired
    private FinanceFlowRepository flowRepository;

    public List<FinanceAccount> findAll() {
        return accountRepository.findAll();
    }

    public Page<FinanceAccount> findAll(Pageable pageable) {
        Page<FinanceAccount> page = accountRepository.findAllByOrderByFlowDateDesc(pageable);
        page.forEach(financeAccount -> {
            financeAccount.setFlows(flowRepository.findAllByFinanceAccountIdOrderByFlowDateDesc(financeAccount.getId()));
        });
        return page;
    }

    public Optional<FinanceAccount> findById(Integer id) {
        Optional<FinanceAccount> optional = accountRepository.findById(id);
        optional.ifPresent(account -> account.setFlows(flowRepository.findAllByFinanceAccountIdOrderByFlowDateDesc(account.getId())));
        return accountRepository.findById(id);
    }

    public void deleteById(Integer id) {
        accountRepository.deleteById(id);
    }

    @Transactional
    public void deleteFlowById(Integer id) {
        FinanceFlow flow = flowRepository.findById(id).get();
        List<FinanceFlow> list = flowRepository.findAllByFinanceAccountIdOrderByFlowDateDesc(flow.getFinanceAccountId());

        // 删除该条数据
        FinanceAccount account = accountRepository.findById(flow.getFinanceAccountId()).get();
        account.setBalance(account.getBalance().subtract(flow.getInAmount()).add(flow.getOutAmount()));

        flowRepository.deleteById(id);
        // 如果该账户下没有数据，则删除该账户
        if (list.size() == 1) {
            accountRepository.deleteById(flow.getFinanceAccountId());
        }

    }

    public void saveFlow(FinanceFlow flow) {
        //更新flow
        if (flow.getId()!= null) {
            Optional<FinanceFlow> optional = flowRepository.findById(flow.getId());
            if (optional.isPresent()) {
                FinanceFlow oldFlow = optional.get();
                FinanceAccount account = accountRepository.findById(oldFlow.getFinanceAccountId()).get();
                // 先减去旧数据的影响
                account.setBalance(account.getBalance().subtract(oldFlow.getInAmount()).add(oldFlow.getOutAmount()));
                // 再加上新数据的影响
                account.setBalance(account.getBalance().add(flow.getInAmount()).subtract(flow.getOutAmount()));

                accountRepository.save(account);
            }
            flowRepository.save(flow);
            return;
        }

        //添加flow
        Optional<FinanceAccount> optional =
                accountRepository.findByCompanyNameAndFlowDate(flow.getCompanyName(), flow.getFlowDate());
        if (optional.isPresent()) {
            FinanceAccount account = optional.get();
            flow.setFinanceAccountId(account.getId());
            account.setBalance(account.getBalance().add(flow.getInAmount()).subtract(flow.getOutAmount()));
            accountRepository.save(account);
        } else {
            FinanceAccount account = new FinanceAccount();
            account.setCompanyName(flow.getCompanyName());
            account.setFlowDate(flow.getFlowDate());
            account.setBalance(flow.getInAmount().subtract(flow.getOutAmount()));
            account = accountRepository.save(account);
            flow.setFinanceAccountId(account.getId());
        }
        flowRepository.save(flow);
    }

}